package com.wj.config.redis;

import com.wj.utils.ContextUtil;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;

import java.util.concurrent.locks.ReadWriteLock;

/**
 * 查询菜单的redis缓存实现
 */
public class RedisCacheConfig implements Cache {
    private final String id;

    public RedisCacheConfig(String id) {
        this.id=id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        ValueOperations op = getValueOperations();
        op.set(compress(key.toString()),value);
    }

    @Override
    public Object getObject(Object key) {
        ValueOperations op = getValueOperations();
        Object res = op.get(compress(key.toString()));
        return res;
    }

    @Override
    public Object removeObject(Object o) {
        return null;
    }

    @Override
    public void clear() {
    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return null;
    }

    public ValueOperations getValueOperations(){
        RedisTemplate<String,Object> template = ContextUtil.getBean("redisTemplate",RedisTemplate.class);
        return template.opsForValue();
    }

    public String compress(String str){
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }
}
